package fun.rockchen.aop;

import fun.rockchen.utils.JwtUtil;
import fun.rockchen.utils.responseUtils.ResponseJson;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


/**
 * @author Rock Chen
 * @Description:
 * @date 2023/10/2 17:32
 */

@Aspect
@Component
public class TokenValidateAspect {
    /**
     * 定义切点
     * Controller层切点 注解拦截
     */
    @Pointcut("@annotation(fun.rockchen.anno.TokenValidate) || @within(fun.rockchen.anno.TokenValidate)")
    public void tokenValidatePointCut() {
    }

    /**
     * 切面
     */
    @Around(value = "tokenValidatePointCut()")
    public Object before(ProceedingJoinPoint joinPoint) throws Throwable {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        String token = request.getHeader("token");
        if (token != null) {
            boolean result = JwtUtil.verify(token);
            if (!result) {
                return ResponseEntity.status(ResponseJson.TokenExpired().getCode()).body( ResponseJson.TokenExpired().getMessage());
            } else {
                return joinPoint.proceed();
            }
        } else {
            return ResponseEntity.status(ResponseJson.NotLogin().getCode()).body( ResponseJson.NotLogin().getMessage());
        }
    }
}
